<template>
  <div>
    <el-row>
      <h4><b>抄送人设置</b></h4>
    </el-row>
    <el-row>
      <div >
        <el-tag v-for="(user,idx) in selectedUser" :key="idx" effect="plain" closable  @close="deleteUser(idx)">
          {{user.nickName}}
        </el-tag>
        <div class="element-drawer__button">
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="onSelectUsers()">添加用户</el-button>
        </div>
      </div>
    </el-row>

    <!-- 候选用户弹窗 -->
    <el-dialog title="候选用户" :visible.sync="userOpen" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :span="7">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>部门列表</span>
            </div>
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
              />
              <el-tree
                :data="deptOptions"
                :props="deptProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="17">
          <el-table ref="multipleTable" height="600" :data="userTableList" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户名" align="center" prop="nickName" />
            <el-table-column label="部门" align="center" prop="dept.deptName" />
          </el-table>
          <pagination
            :total="userTotal"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getUserList"
          />
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleTaskUserComplete">确 定</el-button>
        <el-button @click="userOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { listUser, deptTreeSelect } from "@/api/system/user";
import TreeSelect from "@/components/TreeSelect";


export default {
  name: "UserTaskCopy",
  props: {
    id: String,
    type: String,
    userTaskCopy: Object
  },
  components: { TreeSelect },
  data() {
    return {
      loading: false,
      selectedUser: [],
      userOpen: false,
      deptName: undefined,
      deptOptions: [],
      deptProps: {
        children: "children",
        label: "label"
      },
      deptTempOptions: [],
      userTableList: [],
      userTotal: 0,
      selectedUserDate: [],
      deptTreeData: [],
      deptIds: [],
      // 查询参数
      queryParams: {
        deptId: undefined
      },
      isSequential: false,
      multiLoopType: 'Null',
    };
  },
  watch: {
    id: {
      immediate: true,
      handler() {
        this.bpmnElement = window.bpmnInstances.bpmnElement;
        this.$nextTick(() => this.resetTaskForm());
      }
     },
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
     }
  },
  beforeDestroy() {
    this.bpmnElement = null;
  },
  methods: {
    resetTaskForm() {
      const bpmnElementObj = this.bpmnElement?.businessObject;
      if (!bpmnElementObj) {
        return;
      }
      this.clearOptionsData()
      this.selectedUser = this.userTaskCopy.users || [];
    },
    /**
     * 清空选项数据
     */
    clearOptionsData() {
      this.selectedUser = [];
      this.deptIds = [];
    },
    /**
     * 跟新节点数据
     */
    updateElementTask() {
      console.log("节点id：" + this.id)
      if (this.selectedUser.length > 0){
        let  copyData = {
          nodeKey: this.id,
          users: this.selectedUser
        }
        this.$emit('save',copyData);
      }

    },
    /**
     * 查询部门下拉树结构
     */
    getDeptOptions() {
      return new Promise((resolve, reject) => {
        if (!this.deptOptions || this.deptOptions.length <= 0) {
          deptTreeSelect().then(response => {
            this.deptTempOptions = response.data;
            this.deptOptions = response.data;
            resolve()
          })
        } else {
          reject()
        }
      });
    },
    /** 查询用户列表 */
    getUserList() {
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userTableList = response.rows;
        this.userTotal = response.total;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getUserList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedUserDate = selection;
    },
    onSelectUsers() {
      this.selectedUserDate = []
      this.$refs.multipleTable?.clearSelection();
      this.getDeptOptions();
      this.userOpen = true;
    },
    handleTaskUserComplete() {
      if (!this.selectedUserDate || this.selectedUserDate.length <= 0) {
        this.$modal.msgError('请选择用户');
        return;
      }
      if (this.selectedUserDate.length >0){
        this.selectedUserDate.forEach(item => {
          let u = {
            userId: item.userId,
            nickName: item.nickName
          }
         this.addSelectedUser(u)
        })
      }
      this.updateElementTask()
      this.userOpen = false;
    },

    addSelectedUser(u){
      if (this.selectedUser.length > 0 ){
        let isExist = false;
        for (let i = 0 ;i < this.selectedUser.length ; i++){
          let item = this.selectedUser[i];
          if (item.userId == u.userId){
            isExist = true
            break
          }
        }
        if (!isExist){
          this.selectedUser.push(u)
        }
      }else {
        this.selectedUser.push(u)
      }
    },

    deleteUser(idx){
      this.selectedUser.splice(idx,1);
    }
  }
};
</script>

<style scoped lang="scss">
.el-row .el-radio-group {
  margin-bottom: 15px;
  .el-radio {
    line-height: 28px;
  }
}
.el-tag {
  margin-bottom: 10px;
  + .el-tag {
    margin-left: 10px;
  }
}

.custom-label {
  padding-left: 5px;
  font-weight: 500;
  font-size: 14px;
  color: #606266;
}

</style>
